package com.lcw.lostandfound.util;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
import java.util.UUID;


/**
 * @author lcw
 */
public class RandomCodeUtils {

    public static void createRandomCode(HttpServletRequest req, HttpServletResponse resp) {
        //生成随机数
        String randomCode= UUID.randomUUID().toString().substring(0, 4);
        //System.out.println(randomCode);
        //把随机数放进Session中
        req.getSession().setAttribute("RANDOMCODE_IN_SESSION", randomCode);

        //创建图片对象
        int width=80;
        int height=27;
        int imageType= BufferedImage.TYPE_INT_BGR;
        BufferedImage image=new BufferedImage(width, height, imageType);

        //画板
        Graphics g=image.getGraphics();
        g.setColor(new Color(77, 139, 188));
        //绘制一个实心的矩形
        g.fillRect(1, 1, width-2, height-2);

        //把随机数画进图片中
        g.setColor(Color.BLACK);//设置随机数的颜色
        Font font=new Font("宋体", Font.BOLD+Font.ITALIC, 20);
        g.setFont(font);//设置随机数的字体和大小
        g.drawString(randomCode, 10, 20);
        //干扰线
        g.setColor(Color.GRAY);
        Random r=new Random();
        for(int i=0;i<10;i++){
            g.fillRect(r.nextInt(width), r.nextInt(height), 2, 2);
        }
        //关闭
        g.dispose();
        try{
            //把图片对象以流的方式保存出去
            ImageIO.write(image, "jpg", resp.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
